<template>
  <view class="calendar-reward-page">
    <!-- 头部标题 -->
    <view class="header">
      <text class="title">宝贝表现记录</text>
      <text class="subtitle">每天记录孩子的成长点滴</text>
    </view>

    <!-- 日历区域 -->
    <view class="calendar-section">
      <view class="calendar-header">
        <view class="month-nav" @click="previousMonth">
          <text class="nav-btn">‹</text>
        </view>
        <text class="current-month">{{ currentYear }}年{{ currentMonth }}月</text>
        <view class="month-nav" @click="nextMonth">
          <text class="nav-btn">›</text>
        </view>
      </view>

      <view class="calendar-weekdays">
        <text class="weekday" v-for="day in weekdays" :key="day">{{ day }}</text>
      </view>

      <view class="calendar-days">
        <view 
          v-for="(day, index) in calendarDays" 
          :key="index"
          :class="['calendar-day', getDayClass(day)]"
          @click="selectDate(day)"
        >
          <text class="day-number" v-if="day">{{ day.day }}</text>
          <view class="day-rating" v-if="day && day.rating">
            <text class="rating-icon">{{ getRatingIcon(day.rating) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 评价区域 -->
    <view class="rating-section" v-if="selectedDate && isToday(selectedDate)">
      <view class="rating-title">
        <text>今日表现评价</text>
        <text class="selected-date">{{ formatDate(selectedDate) }}</text>
      </view>
      
      <view class="rating-types">
        <view 
          v-for="type in ratingTypes" 
          :key="type.value"
          :class="['rating-type', selectedRating === type.value ? 'selected' : '']"
          @click="selectRating(type.value)"
        >
          <text class="rating-emoji">{{ type.emoji }}</text>
          <text class="rating-label">{{ type.label }}</text>
          <text class="rating-desc">{{ type.desc }}</text>
        </view>
      </view>

      <button 
        class="save-rating-btn" 
        :disabled="!selectedRating"
        @click="saveRating"
      >
        保存今日评价
      </button>
    </view>

    <!-- 历史评价查看 -->
    <view class="history-section" v-if="selectedDate && !isToday(selectedDate) && selectedDate.rating">
      <view class="history-title">
        <text>{{ formatDate(selectedDate) }} 的表现</text>
      </view>
      <view class="history-rating">
        <text class="history-emoji">{{ getRatingIcon(selectedDate.rating) }}</text>
        <text class="history-label">{{ getRatingLabel(selectedDate.rating) }}</text>
      </view>
    </view>

    <!-- 月度统计 -->
    <view class="monthly-stats">
      <view class="stats-title">本月统计</view>
      <view class="stats-content">
        <view class="stat-item">
          <text class="stat-emoji">⭐</text>
          <text class="stat-count">{{ monthlyStats.fiveStars }}</text>
          <text class="stat-label">五角星</text>
        </view>
        <view class="stat-item">
          <text class="stat-emoji">▲</text>
          <text class="stat-count">{{ monthlyStats.triangleStars }}</text>
          <text class="stat-label">三角星</text>
        </view>
        <view class="stat-item">
          <text class="stat-emoji">✗</text>
          <text class="stat-count">{{ monthlyStats.crosses }}</text>
          <text class="stat-label">大叉</text>
        </view>
      </view>

      <!-- 奖励提示 -->
      <view class="reward-section">
        <view class="reward-item" v-if="monthlyStats.fiveStars >= 5">
          <text class="reward-icon">🎉</text>
          <text class="reward-text">五角星已满5个，获得奖励！</text>
        </view>
        <view class="reward-item" v-if="monthlyStats.triangleStars >= 10">
          <text class="reward-icon">🏆</text>
          <text class="reward-text">三角星已满10个，获得奖励！</text>
        </view>
      </view>
    </view>

    <!-- DeepSeek API预留提示 -->
    <view class="api-note">
      <text class="note-text">注：当前使用本地存储，后续将接入DeepSeek AI分析</text>
    </view>
  </view>
</template>

<script>
import { getShareAppMessageConfig, getShareTimelineConfig } from '../../utils/share.js'

export default {
  data() {
    return {
      currentYear: new Date().getFullYear(),
      currentMonth: new Date().getMonth() + 1,
      selectedDate: null,
      selectedRating: null,
      weekdays: ['日', '一', '二', '三', '四', '五', '六'],
      ratingTypes: [
        { 
          value: 'fiveStar', 
          label: '五角星', 
          emoji: '⭐',
          desc: '表现优秀'
        },
        { 
          value: 'triangleStar', 
          label: '三角星', 
          emoji: '▲',
          desc: '表现良好'
        },
        { 
          value: 'cross', 
          label: '大叉', 
          emoji: '✗',
          desc: '需要改进'
        }
      ],
      monthlyStats: {
        fiveStars: 0,
        triangleStars: 0,
        crosses: 0
      }
    }
  },

  computed: {
    calendarDays() {
      return this.generateCalendarDays()
    }
  },

  mounted() {
    this.initTodaySelection()
    this.calculateMonthlyStats()
  },

  methods: {
    // 生成日历天数数据
    generateCalendarDays() {
      const days = []
      const firstDay = new Date(this.currentYear, this.currentMonth - 1, 1)
      const lastDay = new Date(this.currentYear, this.currentMonth, 0)
      const startDate = firstDay.getDay()
      
      // 获取评价数据
      const ratings = this.getMonthlyRatings()
      
      // 填充空白
      for (let i = 0; i < startDate; i++) {
        days.push(null)
      }
      
      // 填充日期
      for (let day = 1; day <= lastDay.getDate(); day++) {
        const dateStr = `${this.currentYear}-${String(this.currentMonth).padStart(2, '0')}-${String(day).padStart(2, '0')}`
        days.push({
          day,
          date: dateStr,
          rating: ratings[dateStr] || null
        })
      }
      
      return days
    },

    // 分享配置
    onShareAppMessage() {
      return getShareAppMessageConfig({
        title: '宝贝表现记录 - 安记录丨工具舱',
        path: '/pages-sub/calendar-reward/index',
        imageUrl: '/static/share-img.png'
      })
    },

    onShareTimeline() {
      return getShareTimelineConfig({
        title: '宝贝表现记录 - 安记录丨工具舱',
        imageUrl: '/static/share-img.png'
      })
    },

    initTodaySelection() {
      const today = new Date()
      const todayStr = this.formatDateStr(today)
      const todayData = {
        day: today.getDate(),
        date: todayStr,
        rating: this.getRatingForDate(todayStr)
      }
      this.selectedDate = todayData
    },

    previousMonth() {
      if (this.currentMonth === 1) {
        this.currentMonth = 12
        this.currentYear--
      } else {
        this.currentMonth--
      }
      this.calculateMonthlyStats()
    },

    nextMonth() {
      if (this.currentMonth === 12) {
        this.currentMonth = 1
        this.currentYear++
      } else {
        this.currentMonth++
      }
      this.calculateMonthlyStats()
    },

    selectDate(day) {
      if (!day) return
      // 创建选中日期的副本，避免直接修改日历数据
      this.selectedDate = day ? {
        day: day.day,
        date: day.date,
        rating: day.rating
      } : null
      this.selectedRating = day ? day.rating : null
    },

    selectRating(rating) {
      this.selectedRating = rating
    },

    saveRating() {
      if (!this.selectedDate || !this.selectedRating) return

      try {
        const key = `child_rating_${this.selectedDate.date}`
        uni.setStorageSync(key, {
          rating: this.selectedRating,
          timestamp: Date.now()
        })

        // 更新选中日期的评分
        this.selectedDate.rating = this.selectedRating
        
        // 重新计算月度统计
        this.calculateMonthlyStats()

        uni.showToast({
          title: '评价保存成功！',
          icon: 'success'
        })
      } catch (e) {
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'none'
        })
      }
    },

    getDayClass(day) {
      if (!day) return ''
      const classes = []
      
      const today = new Date()
      const dayDate = new Date(day.date)
      
      if (this.isToday(day)) {
        classes.push('today')
      }
      
      if (this.selectedDate && this.selectedDate.date === day.date) {
        classes.push('selected')
      }
      
      if (this.isFuture(day)) {
        classes.push('future')
      }
      
      if (day.rating) {
        classes.push(`rated-${day.rating}`)
      }
      
      return classes.join(' ')
    },

    isToday(day) {
      if (!day) return false
      const today = new Date()
      return day.date === this.formatDateStr(today)
    },

    isFuture(day) {
      if (!day) return false
      const today = new Date()
      const dayDate = new Date(day.date)
      return dayDate > today
    },

    getRatingIcon(rating) {
      const type = this.ratingTypes.find(t => t.value === rating)
      return type ? type.emoji : ''
    },

    getRatingLabel(rating) {
      const type = this.ratingTypes.find(t => t.value === rating)
      return type ? type.label : ''
    },

    formatDate(dateObj) {
      if (!dateObj) return ''
      const date = new Date(dateObj.date)
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
    },

    formatDateStr(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    getMonthlyRatings() {
      const ratings = {}
      try {
        const keys = uni.getStorageInfoSync().keys
        keys.forEach(key => {
          if (key.startsWith('child_rating_')) {
            const dateStr = key.replace('child_rating_', '')
            const [year, month] = dateStr.split('-')
            if (parseInt(year) === this.currentYear && parseInt(month) === this.currentMonth) {
              const data = uni.getStorageSync(key)
              ratings[dateStr] = data.rating
            }
          }
        })
      } catch (e) {
        console.error('获取月度评价失败', e)
      }
      return ratings
    },

    getRatingForDate(dateStr) {
      try {
        const key = `child_rating_${dateStr}`
        const data = uni.getStorageSync(key)
        return data ? data.rating : null
      } catch (e) {
        return null
      }
    },

    calculateMonthlyStats() {
      const ratings = this.getMonthlyRatings()
      this.monthlyStats = {
        fiveStars: 0,
        triangleStars: 0,
        crosses: 0
      }
      
      Object.values(ratings).forEach(rating => {
        if (rating === 'fiveStar') this.monthlyStats.fiveStars++
        else if (rating === 'triangleStar') this.monthlyStats.triangleStars++
        else if (rating === 'cross') this.monthlyStats.crosses++
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// 温馨可爱主题色
$primary: #ff6b6b;
$secondary: #4ecdc4;
$accent: #45b7d1;
$warning: #ffd93d;
$success: #6bcf7f;
$danger: #ff8b94;
$bg: #fff5f5;
$card-bg: #ffffff;
$shadow: 0 8rpx 32rpx rgba(255, 107, 107, 0.1);
$radius: 24rpx;

.calendar-reward-page {
  min-height: 100vh;
  background: linear-gradient(135deg, $bg 0%, #fff 100%);
  padding: 40rpx 32rpx;
}

.header {
  text-align: center;
  margin-bottom: 48rpx;

  .title {
    font-size: 48rpx;
    font-weight: bold;
    color: $primary;
    display: block;
    margin-bottom: 12rpx;
  }

  .subtitle {
    font-size: 28rpx;
    color: #999;
    display: block;
  }
}

.calendar-section {
  background: $card-bg;
  border-radius: $radius;
  box-shadow: $shadow;
  padding: 32rpx;
  margin-bottom: 32rpx;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;

  .month-nav {
    padding: 16rpx 24rpx;
    background: $primary;
    border-radius: 20rpx;
    
    .nav-btn {
      color: white;
      font-size: 32rpx;
      font-weight: bold;
    }
  }

  .current-month {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.calendar-weekdays {
  display: flex;
  margin-bottom: 16rpx;

  .weekday {
    flex: 1;
    text-align: center;
    font-size: 28rpx;
    color: #666;
    font-weight: bold;
  }
}

.calendar-days {
  display: flex;
  flex-wrap: wrap;

  .calendar-day {
    width: calc(100% / 7);
    height: 120rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: relative;
    border-radius: 16rpx;
    margin: 8rpx 0;

    .day-number {
      font-size: 28rpx;
      color: #333;
    }

    .day-rating {
      position: absolute;
      top: 8rpx;
      right: 8rpx;

      .rating-icon {
        font-size: 20rpx;
      }
    }

    &.today {
      background: linear-gradient(135deg, #667eea, #764ba2);
      color: white;
      box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
      border: 2rpx solid #667eea;
      
      .day-number {
        color: white;
        font-weight: bold;
        font-size: 32rpx;
      }

      .day-rating {
        position: absolute;
        top: auto;
        bottom: 8rpx;
        left: 50%;
        transform: translateX(-50%);
        background: rgba(255, 255, 255, 0.9);
        border-radius: 50%;
        width: 32rpx;
        height: 32rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .rating-icon {
          font-size: 20rpx;
        }
      }
    }

    &.selected {
      border: 3rpx solid $primary;
    }

    &.future {
      opacity: 0.5;
    }

    &.rated-fiveStar .day-number {
      color: $warning;
      font-weight: bold;
    }

    &.rated-triangleStar .day-number {
      color: $success;
      font-weight: bold;
    }

    &.rated-cross .day-number {
      color: $danger;
      font-weight: bold;
    }
  }
}

.rating-section {
  background: $card-bg;
  border-radius: $radius;
  box-shadow: $shadow;
  padding: 32rpx;
  margin-bottom: 32rpx;
}

.rating-title {
  text-align: center;
  margin-bottom: 32rpx;

  text {
    font-size: 32rpx;
    font-weight: bold;
    color: $primary;
    display: block;
  }

  .selected-date {
    font-size: 24rpx;
    color: #666;
    margin-top: 8rpx;
  }
}

.rating-types {
  display: flex;
  justify-content: space-between;
  margin-bottom: 32rpx;

  .rating-type {
    flex: 1;
    text-align: center;
    padding: 24rpx 16rpx;
    border-radius: 20rpx;
    border: 3rpx solid #f0f0f0;
    margin: 0 8rpx;
    transition: all 0.3s ease;

    &.selected {
      border-color: $primary;
      background: linear-gradient(135deg, rgba(255, 107, 107, 0.1), rgba(78, 205, 196, 0.1));
    }

    .rating-emoji {
      font-size: 48rpx;
      display: block;
      margin-bottom: 8rpx;
    }

    .rating-label {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      display: block;
      margin-bottom: 4rpx;
    }

    .rating-desc {
      font-size: 22rpx;
      color: #999;
      display: block;
    }
  }
}

.save-rating-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, $primary, $secondary);
  color: white;
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: bold;
  
  &[disabled] {
    background: #ccc;
    color: #999;
  }
}

.history-section {
  background: $card-bg;
  border-radius: $radius;
  box-shadow: $shadow;
  padding: 32rpx;
  margin-bottom: 32rpx;
  text-align: center;
}

.history-title {
  font-size: 32rpx;
  font-weight: bold;
  color: $primary;
  margin-bottom: 24rpx;
}

.history-rating {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;

  .history-emoji {
    font-size: 48rpx;
  }

  .history-label {
    font-size: 28rpx;
    color: #333;
  }
}

.monthly-stats {
  background: $card-bg;
  border-radius: $radius;
  box-shadow: $shadow;
  padding: 32rpx;
  margin-bottom: 32rpx;
}

.stats-title {
  font-size: 32rpx;
  font-weight: bold;
  color: $primary;
  text-align: center;
  margin-bottom: 24rpx;
}

.stats-content {
  display: flex;
  justify-content: space-around;
  margin-bottom: 32rpx;
}

.stat-item {
  text-align: center;
  padding: 24rpx;
  border-radius: 20rpx;
  background: linear-gradient(135deg, rgba(255, 107, 107, 0.05), rgba(78, 205, 196, 0.05));

  .stat-emoji {
    font-size: 36rpx;
    display: block;
    margin-bottom: 8rpx;
  }

  .stat-count {
    font-size: 40rpx;
    font-weight: bold;
    color: $primary;
    display: block;
    margin-bottom: 4rpx;
  }

  .stat-label {
    font-size: 24rpx;
    color: #666;
  }
}

.reward-section {
  margin-top: 24rpx;
}

.reward-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: linear-gradient(135deg, $warning, $success);
  border-radius: 20rpx;
  margin-bottom: 16rpx;
  color: white;

  .reward-icon {
    font-size: 32rpx;
    margin-right: 16rpx;
  }

  .reward-text {
    font-size: 28rpx;
    font-weight: bold;
    flex: 1;
  }
}

.api-note {
  text-align: center;
  padding: 24rpx;
  background: rgba(255, 107, 107, 0.05);
  border-radius: 16rpx;
  margin-top: 32rpx;

  .note-text {
    font-size: 24rpx;
    color: #999;
  }
}
</style>